package br.diego.tb.twitter;


public class TweetsPerSecondV2 {
	
	public static void main(String[] args) {
		
		Integer[] tps = {9, 7, 6, 1, 5, 4};
		int k = 3;
		
		tweets_per_second(tps, k);
	}

	public static void tweets_per_second(Integer[] tps, Integer k) 
    {
		// Converting once so java doesn't need to do it everytime
		// I did prefer working with int's.
		
		int expireInterval = k;
	     
        int highest = 0;
    	int highestPosition = 0;
    	
    	
    	for(int secondsPassed = 0; secondsPassed < tps.length; secondsPassed ++)
    	{
    		int actualTps = tps[secondsPassed];
    		
    		if(actualTps > highest)
    		{
    			highest = actualTps;
    			highestPosition = secondsPassed;
    		}
    		
    		if(isHighestExpired(highestPosition, secondsPassed, expireInterval))
    		{
                int nextCandidateIndex = retrieveNewHighestElementIndexFromPreviousK(tps, secondsPassed, k);

    			highest = tps[nextCandidateIndex];
    			highestPosition = nextCandidateIndex;
    		}
    		
			System.out.println(highest);
    	}
    }

	private static boolean isHighestExpired(int highestPosition, int secondsPassed, int expireInterval) 
	{
		if(secondsPassed - highestPosition == expireInterval)
			return true;
		else
			return false;
	}
	
	private static int retrieveNewHighestElementIndexFromPreviousK(Integer[] tps, int secondsPassed, int k)
	{
		int nextCandidate = 0;
        int nextCandidatePosition = 0;
	
        for(int i = secondsPassed - 1; i > secondsPassed -k; i --)
		{
			if(tps[i] > nextCandidate)
			{
	          nextCandidate = tps[i];
	          nextCandidatePosition = i;        
			}
		}
        
        return nextCandidatePosition;
	}
	
}
